import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from '@/utils/request'
import type { ApiResponse } from '@/types/api'
import { formatDateTime } from '@/utils/format'

// 路由
const router = useRouter()
const route = useRoute()

// 加载状态
const loading = ref(false)

// 查询参数
const queryForm = reactive({
  page: 1,
  limit: 10,
})

// 日志列表
const logs = ref<any[]>([])

// 总数
const total = ref(0)

// 返回上一页
const goBack = () => {
  router.back()
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  queryForm.limit = val
  getLogs()
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  queryForm.page = val
  getLogs()
}

// 获取操作日志
const getLogs = async () => {
  try {
    loading.value = true

    const customerId = route.params.id as string

    // 调用新后端接口获取操作日志
    const response: ApiResponse<any[]> = await axios.get(`/api/customer/log/view`, {
      params: {
        customer_id: customerId,
        ...queryForm,
      },
    })

    // 统一从ApiResponse中获取并解析数据
    if (response.code === 0) {
      logs.value = response.data
      total.value = response.count || 0
    } else {
      ElMessage.error(response.msg || '获取操作日志失败')
    }
  } catch (error) {
    ElMessage.error('获取操作日志失败')
  } finally {
    loading.value = false
  }
}

// 初始化数据
const init = () => {
  getLogs()
}

// 组件挂载时初始化
onMounted(() => {
  init()
})

// 导出所有需要在模板中使用的变量和方法
export {
  // 响应式数据
  loading,
  queryForm,
  logs,
  total,

  // 方法
  goBack,
  handleSizeChange,
  handleCurrentChange,
  formatDateTime,
}
